package com.example.food.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.food.adapter.OrderListApter;
import com.example.food.bean.OrderListBean;
import com.example.home.R;
import com.example.home.me.LoginActivity;
import com.example.home.tool.GeneralClass;
import com.example.home.tool.OKHttpTool;
import com.google.android.material.tabs.TabLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;


public class OrderFragment extends Fragment {

    private ImageView img;
    private TabLayout tabList;
    private RecyclerView rcvList;
    private View view;
    private OrderListBean orderListBean;
    private OrderListApter orderListApter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_order2, container, false);

        if (OKHttpTool.TOKEN == "" && OKHttpTool.TOKEN == null){
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            getActivity().startActivity(intent);
        }
        initView();
        
        orderType();
        
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();

        // 在这里执行刷新操作，例如重新加载数据
        orderList("全部");
    }

    private void orderType() {
        ArrayList<String> strings = new ArrayList<>();
        strings.add("全部");
        strings.add("待支付");
        strings.add("待评价");
        strings.add("退款");
        for (String string : strings) {
            TabLayout.Tab tab = tabList.newTab();
            tab.setText(string);
            tabList.addTab(tab);
        }
        orderList(strings.get(0));
        tabList.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                String ordertype = tab.getText().toString();
                int position = tab.getPosition();
                if(ordertype==strings.get(position)){
                    orderList(strings.get(position));
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void orderList(String type) {
        String url  = "prod-api/api/takeout/order/list";
        if(!"全部".equals(type)){
            url =url +"?status=" + type ;
        }
        OKHttpTool.doNetRequest(url,
                OKHttpTool.GET,
                OrderListBean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        orderListBean = (OrderListBean) obj;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if(orderListBean.getCode()==200){
                                    rcvList.setLayoutManager(new LinearLayoutManager(OrderFragment.this.getActivity()));
                                    orderListApter = new OrderListApter(OrderFragment.this.getActivity(), orderListBean.getRows(), new OrderListApter.OnOrderlistClickListener() {
                                        @Override
                                        public void onOrderListClick(String list) {
                                            ToRefund(list);
                                        }

                                        @Override
                                        public void onPrefundListClick(String order) {
                                            Tocomment(order);
                                        }
                                    });
                                    rcvList.setAdapter(orderListApter);
                                }
                            }
                        });
                    }
                    @Override
                    public void onFailure(String msg) {

                    }
                });
    }

    private void ToRefund(String order) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
        View inflate = LayoutInflater.from(this.getActivity()).inflate(R.layout.item_refund, null);
        EditText ed_refund = inflate.findViewById(R.id.ed_refund);
        builder.setView(inflate);
        builder.setTitle("退款说明");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String refund = ed_refund.getText().toString();
                if (!"".equals(refund) || !TextUtils.isEmpty(refund)){
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("content",refund);
                        jsonObject.put("orderNo",order);

                        String string = jsonObject.toString();

                        OKHttpTool.doNetRequest("prod-api/api/takeout/order/refound",
                                OKHttpTool.POST,
                                GeneralClass.class,
                                new OKHttpTool.NetCallback() {
                                    @Override
                                    public void onSuccess(Object obj) {
                                        GeneralClass generalClass = (GeneralClass) obj;
                                        getActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                if(generalClass.getCode()==200){
                                                    Toast.makeText(getActivity(), "退款成功", Toast.LENGTH_SHORT).show();
                                                    refreshList(order);
                                                }
                                            }
                                        });
                                    }
                                    @Override
                                    public void onFailure(String msg) {

                                    }
                                },string);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.create().show();
    }

    private void Tocomment(String list) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.item_comment, null);
        EditText ed_commot = inflate.findViewById(R.id.ed_commot);
        RatingBar bar = inflate.findViewById(R.id.bar);
        builder.setView(inflate);
        builder.setTitle("评论商家");

        bar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                ratingBar.setRating((float)Math.ceil(rating));
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String commit = ed_commot.getText().toString();
                Integer rating = Math.round(bar.getRating());
                if ((!"".equals(commit) || !TextUtils.isEmpty(commit)) && rating != null){
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("content",commit);
                        jsonObject.put("orderNo",list);
                        jsonObject.put("score",rating);

                        String string = jsonObject.toString();

                        OKHttpTool.doNetRequest("prod-api/api/takeout/comment",
                                OKHttpTool.POST,
                                GeneralClass.class,
                                new OKHttpTool.NetCallback() {
                                    @Override
                                    public void onSuccess(Object obj) {
                                        GeneralClass generalClass = (GeneralClass) obj;
                                        getActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                if(generalClass.getCode()==200){
                                                    Toast.makeText(getActivity(), "评论成功", Toast.LENGTH_SHORT).show();
                                                    refreshList(list);
                                                }
                                            }
                                        });
                                    }
                                    @Override
                                    public void onFailure(String msg) {

                                    }
                                },string);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.create().show();
    }

    private void refreshList(String on){
        for(OrderListBean.RowsBean bean:orderListBean.getRows()){
            if(on.equals(bean.getOrderInfo().getOrderNo())){
                bean.getOrderInfo().setStatus("完成");
            }
        }
        //刷新
        orderList("待评价");
        orderListApter.notifyDataSetChanged();
    }

    private void initView() {

        img = view.findViewById(R.id.img);
        tabList = view.findViewById(R.id.tab_list);
        rcvList = view.findViewById(R.id.rcv_list);

        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });

    }
}